<?php

namespace app\api\controller;

use app\api\model\UserModel;
use think\Request;

class LoginController
{
    // 微信小程序 AppID 和 AppSecret
    private $appId = 'wx3b21db4197eacb5f';
    private $appSecret = '557b6a2f1a4435c769a4a194a17c5c24';

    // 微信登录接口（POST请求）
    // 微信登录接口（POST请求）
    public function mobile(Request $request)
    {
        if ($request->isPost()) {
            // 获取前端传递的 code
            $code = $request->post('code');
            if (empty($code)) {
                return json(['status' => 'error', 'message' => 'Code is required']);
            }

            // 构造请求参数
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appId}&secret={$this->appSecret}&js_code={$code}&grant_type=authorization_code";

            // 使用 curl 请求微信接口
            $response = $this->httpRequest($url);
            $phone = $this->bindPhone($request, $response['session_key']);

            $user = new UserModel;


            if (isset($response['openid'])) {
                // 返回 openid 和 session_key
                $row = $user->where('phone', $phone)->find();
                //如果查不到就新增
                if (empty($row)) {
                    $user->data([
                        'name' => $phone,
                        'phone' => $phone
                    ]);
                    $user->save();
                }

                return json([
                    'status' => 'success',
                    'openid' => $response['openid'],
                    'session_key' => $response['session_key'],
                    "user" => $row
                ]);
            } else {
                return json(['status' => 'error', 'message' => 'Login failed']);
            }
        } else {
            return json(['status' => 'error', 'message' => 'Invalid request method, POST expected']);
        }
    }

    // 绑定手机号接口
    public function bindPhone(Request $request, $sessionKey)
    {
        $encryptedData = $request->post('encryptedData');
        $iv = $request->post('iv');

        if (empty($encryptedData) || empty($iv) || empty($sessionKey)) {
            return json(['status' => 'error', 'message' => 'Missing parameters']);
        }

        // 解密手机号
        $phoneNumber = $this->decryptPhoneNumber($sessionKey, $encryptedData, $iv);

        if ($phoneNumber) {
            return $phoneNumber;
        } else {
            return '';
        }
    }

    // 解密手机号
    private function decryptPhoneNumber($sessionKey, $encryptedData, $iv)
    {
        $decrypted = $this->decryptData($sessionKey, $encryptedData, $iv);
        if ($decrypted) {
            // 解密后返回的内容是JSON格式，提取手机号
            $data = json_decode($decrypted, true);
            return $data['phoneNumber'] ?? null;  // 返回手机号
        }
        return null;
    }

    // 解密数据
    private function decryptData($sessionKey, $encryptedData, $iv)
    {
        // base64 decode
        $sessionKey = base64_decode($sessionKey);
        $encryptedData = base64_decode($encryptedData);
        $iv = base64_decode($iv);

        // 使用 AES-128-CBC 解密
        $decrypted = openssl_decrypt($encryptedData, 'AES-128-CBC', $sessionKey, OPENSSL_RAW_DATA, $iv);

        // 验证解密是否成功
        if ($decrypted) {
            return $decrypted;
        } else {
            return false;
        }
    }

    // 发起 HTTP 请求
    private function httpRequest($url)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);

        // 允许 SSL 验证，防止 SSL 证书错误导致请求失败（仅用于测试，生产环境需要正确配置证书）
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($curl);

        // 如果发生错误，输出详细的错误信息
        if ($response === false) {
            $error = curl_error($curl);  // 获取错误信息
            $errorCode = curl_errno($curl);  // 获取错误代码
            curl_close($curl);
            return [
                'status' => 'error',
                'message' => 'cURL error: ' . $error . ' (Code: ' . $errorCode . ')'
            ];
        }

        curl_close($curl);

        // 返回响应数据
        return json_decode($response, true);
    }

}
